/**
 * @param {number[][]} matrix
 * @return {number[]}
 */
var spiralOrder = function (matrix) {
  if (matrix.length == 0) {
    return [];
  }

  let l = 0,
    r = matrix[0].length - 1,
    x = 0,
    y = matrix.length - 1;

  const arr = [];

  let len = matrix.length;

  while (l < r && x < y) {
    for (let i = l; i <= r; i++) {
      arr.push(matrix[x][i]);
    }

    x++;

    for (let i = x; i <= y; i++) {
      arr.push(matrix[i][r]);
    }

    r--;

    for (let i = r; i >= l; i--) {
      arr.push(matrix[y][i]);
    }

    y--;

    for (let i = y; i >= x; i--) {
      arr.push(matrix[i][l]);
    }

    l++;
  }

  if (x == y && l < r) {
    for (let i = l; i <= r; i++) {
      arr.push(matrix[x][i]);
    }
  }

  if (l == r && x < y) {
    for (let i = x; i <= y; i++) {
      arr.push(matrix[i][l]);
    }
  }

  if (x == y && l == r) {
    arr.push(matrix[x][r]);
  }

  return arr;
};
